package initialize

import (
	"cgs-server/server/base"
	"cgs-server/server/model"
	"cgs-server/server/system/tenant"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"time"
)

type InitializeService interface {
	base.Service
	Initialize(mdl *model.DataUserModel) error
}

func NewInitializeService() InitializeService {
	return &initializeService{
		configRepo: NewInitializeRepository(),
	}
}

type initializeService struct {
	base.ServiceImpl
	configRepo InitializeRepository
}

func (i *initializeService) Initialize(mdl *model.DataUserModel) error {
	if tenantVo, ok := mdl.Data.(*tenant.TenantVo); ok {
		// 1. 查询
		config := &model.SystemConfig{
			Initialized:         true,
			DefaultRegisterRole: primitive.NewObjectID().Hex(),
		}
		duModel := &model.DataUserModel{
			Data: config,
			User: mdl.User,
		}
		one, err := i.configRepo.FindOne(duModel)
		if err != nil {
			return err
		}
		if one == nil {
			// 没找到，就新增
			err := i.configRepo.Insert(duModel)
			if err != nil {
				return err
			}
			// 新增一个租户
			tenantService := tenant.NewTenantService()
			err = tenantService.Save(mdl)
			if err != nil {
				return err
			}
			// 新增账户信息
			info := &tenant.TenantInfo{}
			isTrial := false
			now := time.Now()
			info.Account = tenant.Account{
				Version:       "",
				BeginDate:     now,
				EndDate:       now.AddDate(1, 0, 0),
				IsTrial:       &isTrial,
				RemainingDays: 0,
			}
			info.TenantId = tenantVo.TenantId

			infoService := tenant.NewTenantInfoService()
			err = infoService.Save(&model.DataUserModel{
				Data: info,
			})
			return err
		} else {
			// 更新
			config.ID = one.(*model.SystemConfig).ID
			err := i.configRepo.Update(duModel)
			return err
		}
	} else {
		return model.NewTypeError("config")
	}
}
